import { EventCallback } from "../types";

// 事件总线类
export class EventBus {
  private events: Map<string, EventCallback[]> = new Map();

  // 监听事件
  on(eventName: string, callback: EventCallback): void {
    if (!this.events.has(eventName)) {
      this.events.set(eventName, []);
    }
    this.events.get(eventName)!.push(callback);
  }

  // 移除事件监听
  off(eventName: string, callback: EventCallback): void {
    const callbacks = this.events.get(eventName);
    if (callbacks) {
      const index = callbacks.indexOf(callback);
      if (index > -1) {
        callbacks.splice(index, 1);
      }
    }
  }

  // 触发事件
  emit(eventName: string, data?: any): void {
    const callbacks = this.events.get(eventName);
    if (callbacks) {
      callbacks.forEach((callback) => {
        try {
          callback(data);
        } catch (error) {
          console.error("事件回调执行错误:", error);
        }
      });
    }
  }

  // 清除所有事件
  clear(): void {
    this.events.clear();
  }
}
